有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java当我尝试打印所有组时,得到“IndexOutOfBoundsException:无组4”

我的代码是

 String regexpr = "(abc)(ab)(cd)";
 String test = "abcabcd";
 Pattern p = Pattern.compile(regexpr);
 Matcher m = p.matcher(test);
 while(m.find ())
 {
     System.out.println(m.group());
 }

此代码将输出为

^{pr2}$

但我想打印匹配字符串中的所有组,即

group 1 abc
group 2 ab
group 3 cd

我试过这个

int i=1;
while (m.group(i) != null)
{
    System.out.println("group" + i + m.group(i));
    i++;
}

我要走了

group 1 abc
group 2 ab
group 3 cd
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 4

我怎样才能避免这个例外

如何打印所有组的开始索引和结束索引


共 (2) 个答案

  1. # 1 楼答案

    您可以按以下方式打印所有组的开始索引和结束索引:

       while (i<=m.groupCount())
           {
               System.out.println("group" + i + m.group(i));
               System.out.println("starting index:" + m.start(i) + "Ending Index:" + m.end(i));
               i++;
           }
    
  2. # 2 楼答案

    问题是当i增加到4时,您仍在检查:

    m.group(i) != null
    

    但没有这样的第四组

    一种解决方案是使用^{}

    while (i < m.groupCount() + 1) {
        System.out.println("group " + i + ": " + m.group(i));
        i++;
    }